"""
主应用程序 - 接口自动化测试系统
"""
import sys
import os
from typing import List

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from config.config import settings
from utils.logger import app_logger
from models.database import create_tables
from src.auth.auth_manager import auth_manager
from src.metadata.metadata_manager import metadata_manager
from src.ai.test_case_generator import test_case_generator

class APITestSystem:
    """API自动化测试系统"""
    
    def __init__(self):
        self.initialized = False
        
    def initialize(self) -> bool:
        """
        初始化系统
        
        Returns:
            是否成功初始化
        """
        try:
            app_logger.info("开始初始化API自动化测试系统")
            
            # 1. 创建数据库表
            app_logger.info("创建数据库表...")
            create_tables()
            
            # 2. 初始化认证管理器
            app_logger.info("初始化认证管理器...")
            auth_success = auth_manager.initialize()
            if not auth_success:
                app_logger.error("认证管理器初始化失败")
                return False
            
            self.initialized = True
            app_logger.info("API自动化测试系统初始化成功")
            return True
            
        except Exception as e:
            app_logger.error(f"系统初始化失败: {str(e)}")
            return False
    
    def process_object(self, object_name: str) -> bool:
        """
        处理单个对象的完整流程（前3个阶段）
        
        Args:
            object_name: 对象名称
            
        Returns:
            是否成功
        """
        if not self.initialized:
            app_logger.error("系统未初始化")
            return False
        
        try:
            app_logger.info(f"开始处理对象: {object_name}")
            
            # 阶段2: 获取和处理元数据
            app_logger.info("阶段2: 获取和处理元数据")
            metadata_success = metadata_manager.process_object_metadata(object_name)
            if not metadata_success:
                app_logger.error(f"元数据处理失败: {object_name}")
                return False
            
            # 阶段3: 生成AI测试用例
            app_logger.info("阶段3: 生成AI测试用例")
            test_case_success = test_case_generator.process_test_case_generation(object_name)
            if not test_case_success:
                app_logger.error(f"测试用例生成失败: {object_name}")
                return False
            
            app_logger.info(f"对象处理完成: {object_name}")
            return True
            
        except Exception as e:
            app_logger.error(f"处理对象异常: {str(e)}")
            return False
    
    def process_objects(self, object_names: List[str]) -> bool:
        """
        批量处理多个对象
        
        Args:
            object_names: 对象名称列表
            
        Returns:
            是否全部成功
        """
        if not self.initialized:
            app_logger.error("系统未初始化")
            return False
        
        success_count = 0
        total_count = len(object_names)
        
        for object_name in object_names:
            if self.process_object(object_name):
                success_count += 1
        
        app_logger.info(f"批量处理完成: {success_count}/{total_count} 个对象处理成功")
        return success_count == total_count
    
    def get_system_status(self) -> dict:
        """
        获取系统状态
        
        Returns:
            系统状态信息
        """
        return {
            "initialized": self.initialized,
            "auth_token_available": auth_manager.token is not None,
            "database_url": settings.database_url.replace(settings.DB_PASSWORD, "***"),
            "ai_model": settings.OPENAI_MODEL,
            "metadata_url": settings.METADATA_URL,
            "auth_url": settings.AUTH_URL
        }
    
    def get_object_info(self, object_name: str) -> dict:
        """
        获取对象信息
        
        Args:
            object_name: 对象名称
            
        Returns:
            对象信息
        """
        try:
            # 获取元数据
            metadata = metadata_manager.get_stored_metadata(object_name)
            if not metadata:
                return {"error": f"未找到对象'{object_name}'的元数据"}
            
            # 获取测试用例
            test_cases = test_case_generator.get_test_cases(object_name)
            
            return {
                "object_name": object_name,
                "metadata": metadata,
                "test_cases_count": len(test_cases),
                "test_cases": test_cases
            }
            
        except Exception as e:
            return {"error": f"获取对象信息失败: {str(e)}"}

def main():
    """主函数 - 演示系统使用"""
    system = APITestSystem()
    
    # 初始化系统
    if not system.initialize():
        print("系统初始化失败，请检查配置")
        return
    
    # 获取系统状态
    status = system.get_system_status()
    print("系统状态:")
    for key, value in status.items():
        print(f"  {key}: {value}")
    
    # 示例：处理单个对象
    # object_name = "User"  # 替换为实际的对象名称
    # success = system.process_object(object_name)
    # if success:
    #     print(f"对象'{object_name}'处理成功")
    #     object_info = system.get_object_info(object_name)
    #     print(f"生成了 {object_info['test_cases_count']} 个测试用例")
    # else:
    #     print(f"对象'{object_name}'处理失败")
    
    print("\n系统准备就绪！")
    print("请使用以下方式调用系统功能：")
    print("1. system.process_object('对象名称') - 处理单个对象")
    print("2. system.process_objects(['对象1', '对象2']) - 批量处理对象")
    print("3. system.get_object_info('对象名称') - 获取对象信息")

if __name__ == "__main__":
    main() 